package f_Collectors类.groupingBy方法的使用;

import z_Entity.User;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 使用 Collectors.groupingBy 将Stream流按照指定规则进行分组
 *
 * @author xuyaxu
 * @date 2022/8/27 12:46
 */
public class GroupingByDemo {
    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "jack", 18, 0));
        userList.add(new User(2, "rose", 20, 1));
        userList.add(new User(3, "huahua", 2, 0));
        userList.add(new User(4, "xiaocao", 2, 1));

        // 将用户列表数据进行按照年龄进行分组，然后将对应的数据收集到集合中
        Map<Integer, List<User>> groupingBy = userList.stream().collect(Collectors.groupingBy(User::getAge));
        System.out.println("groupingBy=" + groupingBy);

        // 分完组后使用 mapping 映射id到集合中
        Map<Integer, List<Integer>> mapping =
                userList.stream().collect(Collectors.groupingBy(User::getAge, Collectors.mapping(User::getId, Collectors.toList())));
        System.out.println("mapping=" + mapping);

        // 按照性别进行分组，再将分组后的用户年龄进行相加
        Map<Integer, Integer> summingInt = userList.stream().collect(Collectors.groupingBy(User::getGender, Collectors.summingInt(User::getAge)));
        System.out.println("summingInt" + summingInt);
    }
}
